package cron

import (
	"database/sql"
	"strconv"
	"time"
	"zimuzu_cvn_web_api/config"
	"zimuzu_cvn_web_api/model"
	. "zimuzu_cvn_web_api/pkg/e"
	"zimuzu_cvn_web_api/service"
)

//CVNT充值
func CvntRecharge() {
	var (
		noticeData model.TransferNotice
		name       = "CvntRecharge"
		params     = make(map[string]string)
	)
	Log("info", name, " start")
	//上锁
	if ok := service.Lock(name); !ok {
		Log("err", name, " 程序执行中")
		return
	}
	//释放锁
	defer service.UnLock(name)
	//获取未处理记录列表
	list, err := model.GetTransferNoticeWaitList(config.C.DB.DB, COIN_NAME_CVNT)
	if err != nil {
		Log("err", name, err)
		return
	}
	//迭代
	for _, row := range list {
		Log("info", name, " 开始处理 ID：", row.NoticeId)
		//调用支付网关接口：获取充值信息
		params["id"] = row.NoticeId
		res, err := model.GatewayRequest("GET", ApiRechargeInfo, params, nil)
		if err != nil {
			continue
		}
		//数据处理
		noticeData.NoticeId = row.NoticeId
		noticeData.NextRequestTime = NextRequestTime(row.RequestNum)
		noticeData.TransStatus = res.Data.Result.Status
		noticeData.Status = 1
		//检查收款账户是否存在
		userWalletAddress, _, err := service.GetCheckAddress(res.Data.Result.Address)
		if err != nil {
			continue
		}
		if userWalletAddress.Uid <= 0 {
			Log("err", name, " 收款账户不存在")
			_ = model.UpdateTransferNotice(config.C.DB.DB, noticeData)
			continue
		}
		//检查RelateId
		ok, err := model.ExistCvnLogRelated(config.C.DB.DB, row.NoticeId, model.LogSourceIn)
		if err != nil {
			continue
		}
		if ok {
			Log("err", name, " RelateId 已存在")
			_ = model.UpdateTransferNotice(config.C.DB.DB, noticeData)
			continue
		}
		//检查TxHash
		ok, err = model.ExistCvnLogTxHash(config.C.DB.DB, res.Data.Result.TxId)
		if err != nil {
			continue
		}
		if ok {
			Log("err", name, " TxHash 已存在")
			_ = model.UpdateTransferNotice(config.C.DB.DB, noticeData)
			continue
		}
		//根据状态进行相应处理
		if res.Data.Result.Status == "pending" {
			noticeData.Status = 0
			_ = model.UpdateTransferNotice(config.C.DB.DB, noticeData)
		} else if res.Data.Result.Status == "success" {
			amount, _ := strconv.ParseFloat(res.Data.Result.AbsAmount, 64)
			//开启事务
			tx, err := config.C.DB.DB.Beginx()
			if err != nil {
				continue
			}
			//修改通知状态
			err = model.UpdateTransferNotice(config.C.DB.DB, noticeData)
			if err != nil {
				_ = tx.Rollback()
				continue
			}
			//修改账户金额，增加日志
			updateAmountData := service.UpdateCvnAmountParams{
				Uid:              userWalletAddress.Uid,
				Amount:           amount,
				Source:           model.LogSourceIn,
				RelateId:         row.NoticeId,
				RelateTable:      TableCobo,
				From:             res.Data.Result.SourceAddress,
				To:               res.Data.Result.Address,
				TxHash:           res.Data.Result.TxId,
				Block:            res.Data.Result.TxDetail.BlockNum,
				BlockConfirmTime: res.Data.Result.LastTime / 1000,
			}
			_, err = service.UpdateCvnAmountBalance(tx, updateAmountData)
			if err != nil {
				_ = tx.Rollback()
				continue
			}
			if err = tx.Commit(); err != nil {
				continue
			}
		} else if res.Data.Result.Status == "failed" {
			_ = model.UpdateTransferNotice(config.C.DB.DB, noticeData)
		}
	}
	Log("info", name, " end")
}

//CVNT提现
func CvntTransfer() {
	var (
		requestPre string
		name       = "CvntWithdraw"
		params     = make(map[string]string)
	)
	Log("info", name, " start")
	//上锁
	if ok := service.Lock(name); !ok {
		Log("err", name, " 程序执行中")
		return
	}
	//释放锁
	defer service.UnLock(name)
	//获取未处理记录列表
	list, err := model.GetCvnLogWaitList(config.C.DB.DB)
	if err != nil {
		Log("err", name, err)
		return
	}
	//迭代
	for _, row := range list {
		Log("info", name, " 开始处理ID：", row.Id)
		//获取审核状态
		cvnExamine, err := model.GetCvnExamineByLogId(config.C.DB.DB, row.Id)
		if err != nil && err != sql.ErrNoRows {
			continue
		}
		//根据审核状态进行相应逻辑处理
		if cvnExamine.Status == model.DealStatusCheck {
			continue
		} else if cvnExamine.Status == model.DealStatusFail {
			continue
		}
		//调用支付网关接口：获取提现信息
		if row.Id > config.C.LogId.Cvnt {
			requestPre = COIN_NAME_CVNT + "_"
		}
		params["requestId"] = requestPre + strconv.FormatInt(row.Id, 10)
		res, err := model.GatewayRequest("GET", ApiTransferInfo, params, nil)
		if err != nil && res.Data.ErrorCode != 12004 {
			continue
		}
		if res.Data.ErrorCode == 12004 && time.Now().Unix()-row.CreateTime < TimeFormatHour {
			continue
		}
		//数据处理
		row.TxHash = res.Data.Result.TxId
		row.Block = res.Data.Result.TxDetail.BlockNum
		row.BlockConfirmTime = res.Data.Result.LastTime / 1000
		//确认中
		if res.Data.Result.Status == "pending" {
			service.CvnTransferPending(row)
		} else if res.Data.Result.Status == "success" {
			service.CvnTransferSuccess(row)
		} else if res.Data.Result.Status == "failed" || res.Data.ErrorCode == 12004 {
			service.CvnTransferFailed(row)
		}
	}
	Log("info", name, " end")
}

//USDT充值
func UsdtRecharge() {
	var (
		noticeData model.TransferNotice
		name       = "UsdtRecharge"
		params     = make(map[string]string)
	)
	Log("info", name, " start")
	//上锁
	if ok := service.Lock(name); !ok {
		Log("err", name, " 程序执行中")
		return
	}
	//释放锁
	defer service.UnLock(name)
	//获取未处理记录列表
	list, err := model.GetTransferNoticeWaitList(config.C.DB.DB, COIN_NAME_USDT)
	if err != nil {
		Log("err", name, err)
		return
	}
	//迭代
	for _, row := range list {
		Log("info", name, " 开始处理 ID：", row.NoticeId)
		//调用支付网关接口：获取充值信息
		params["id"] = row.NoticeId
		res, err := model.GatewayRequest("GET", ApiRechargeInfo, params, nil)
		if err != nil {
			continue
		}
		//数据处理
		noticeData.NoticeId = row.NoticeId
		noticeData.NextRequestTime = NextRequestTime(row.RequestNum)
		noticeData.TransStatus = res.Data.Result.Status
		noticeData.Status = 1
		//检查收款账户是否存在
		userWalletAddress, _, err := service.GetCheckAddress(res.Data.Result.Address)
		if err != nil {
			continue
		}
		if userWalletAddress.Uid <= 0 {
			Log("err", name, " 收款账户不存在")
			_ = model.UpdateTransferNotice(config.C.DB.DB, noticeData)
			continue
		}
		//检查RelateId
		ok, err := model.ExistUsdtLogRelated(config.C.DB.DB, row.NoticeId, model.LogSourceUsdtIn)
		if err != nil {
			continue
		}
		if ok {
			Log("err", name, " RelateId 已存在")
			_ = model.UpdateTransferNotice(config.C.DB.DB, noticeData)
			continue
		}
		//检查TxHash
		ok, err = model.ExistUsdtLogTxHash(config.C.DB.DB, res.Data.Result.TxId)
		if err != nil {
			continue
		}
		if ok {
			Log("err", name, " TxHash 已存在")
			_ = model.UpdateTransferNotice(config.C.DB.DB, noticeData)
			continue
		}
		//根据状态进行相应处理
		if res.Data.Result.Status == "pending" {
			noticeData.Status = 0
			_ = model.UpdateTransferNotice(config.C.DB.DB, noticeData)
		} else if res.Data.Result.Status == "success" {
			amount, _ := strconv.ParseFloat(res.Data.Result.AbsAmount, 64)
			//开启事务
			tx, err := config.C.DB.DB.Beginx()
			if err != nil {
				continue
			}
			//修改通知状态
			err = model.UpdateTransferNotice(config.C.DB.DB, noticeData)
			if err != nil {
				_ = tx.Rollback()
				continue
			}
			//修改账户金额，增加日志
			updateAmountData := service.UpdateUsdtAmountParams{
				Uid:              userWalletAddress.Uid,
				Amount:           amount,
				Source:           model.LogSourceUsdtIn,
				RelateId:         row.NoticeId,
				RelateTable:      TableCobo,
				From:             res.Data.Result.SourceAddress,
				To:               res.Data.Result.Address,
				TxHash:           res.Data.Result.TxId,
				Block:            res.Data.Result.TxDetail.BlockNum,
				BlockConfirmTime: res.Data.Result.LastTime / 1000,
			}
			_, err = service.UpdateUsdtAmountBalance(tx, updateAmountData)
			if err != nil {
				_ = tx.Rollback()
				continue
			}
			if err = tx.Commit(); err != nil {
				continue
			}
		} else if res.Data.Result.Status == "failed" {
			_ = model.UpdateTransferNotice(config.C.DB.DB, noticeData)
		}
	}
	Log("info", name, " end")
}

//USDT提现
func UsdtTransfer() {
	var (
		requestPre string
		name       = "UsdtWithdraw"
		params     = make(map[string]string)
	)
	Log("info", name, " start")
	//上锁
	if ok := service.Lock(name); !ok {
		Log("err", name, " 程序执行中")
		return
	}
	//释放锁
	defer service.UnLock(name)
	//获取未处理记录列表
	list, err := model.GetUsdtLogWaitList(config.C.DB.DB)
	if err != nil {
		Log("err", name, err)
		return
	}
	//迭代
	for _, row := range list {
		Log("info", name, " 开始处理ID：", row.Id)
		//获取审核状态
		usdtExamine, err := model.GetUsdtExamineByLogId(config.C.DB.DB, row.Id)
		if err != nil && err != sql.ErrNoRows {
			continue
		}
		//根据审核状态进行相应逻辑处理
		if usdtExamine.Status == model.DealStatusCheck {
			continue
		} else if usdtExamine.Status == model.DealStatusFail {
			continue
		}
		//调用支付网关接口：获取提现信息
		if row.Id > config.C.LogId.Usdt {
			requestPre = COIN_NAME_USDT + "_"
		}
		params["requestId"] = requestPre + strconv.FormatInt(row.Id, 10)
		res, err := model.GatewayRequest("GET", ApiTransferInfo, params, nil)
		if err != nil && res.Data.ErrorCode != 12004 {
			continue
		}
		if res.Data.ErrorCode == 12004 && time.Now().Unix()-row.CreateTime < TimeFormatHour {
			continue
		}
		//数据处理
		row.TxHash = res.Data.Result.TxId
		row.Block = res.Data.Result.TxDetail.BlockNum
		row.BlockConfirmTime = res.Data.Result.LastTime / 1000
		//确认中
		if res.Data.Result.Status == "pending" {
			service.UsdtTransferPending(row)
		} else if res.Data.Result.Status == "success" {
			service.UsdtTransferSuccess(row)
		} else if res.Data.Result.Status == "failed" || res.Data.ErrorCode == 12004 {
			service.UsdtTransferFailed(row)
		}
	}
	Log("info", name, " end")
}
